using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;                 
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Diagnostics;
using System.Xml;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Ink;
using System.Windows.Media.Animation;
using System.Windows.Controls.Primitives;
using System.Threading;

using Marcelo;
using MeetCommon.Tools;
using MVExplorer.Components;
using MeetCommon.Service;
using MveScreenCapture;

namespace MVExplorer
{
	
	
	
	

	
	public partial class MVEMain : System.Windows.Window
	{
		
		private MeetCommon.Service.MeetServerConnector connector;
		private Components.MoviePlayHistory history = new MoviePlayHistory();

		private const string STR_DND_MOVIEITEM_FORMAT = "MovieItem";
		private const string STR_DND_KEYWORDITEM_FORMAT = "KeywordItem";

        public static readonly RoutedCommand TakeSnapshotCommand = new RoutedCommand("TakeSnapshotCommand", typeof(MVEMain));

        List<MapDrawing> canvass = new List<MapDrawing>();
        Stack<List<MapDrawing>> drawingUndoStack = new Stack<List<MapDrawing>>();
        Stack<List<MapDrawing>> drawingRedoStack = new Stack<List<MapDrawing>>();
        List<MapDrawing> tmpCanvass;

        Int16 mapPage = 1;
        Int16[] bookmarkIds;
        
		
		
		public MVEMain()
		{
			InitializeComponent();

			
			InitMainFrame();
			InitMovieListPanel();
			InitMappingPanel();
			InitKeywordBasketPanel();
			InitMoviePlayer();
			
			
		}

		#region Main Window Frame and Grid Members


		
		
		
		private void InitMainFrame()
		{
			this.Loaded += new RoutedEventHandler(MVEMain_Loaded);
			
            this.Closing += new System.ComponentModel.CancelEventHandler(MVEMain_Closing);
			MainGrid.MouseLeftButtonDown += new MouseButtonEventHandler(MainGrid_MouseLeftButtonDown);
			MainGrid.DragOver += new DragEventHandler(MainGrid_DragOver);
			MainGrid.DragLeave += new DragEventHandler(MainGrid_DragLeave);

            

            cmdLogo.Click += new RoutedEventHandler(OpenMeetMenu);

            
            
            
            

			textSearchKeyword.AllowDrop = true;
			textSearchKeyword.KeyUp += new KeyEventHandler(textSearchKeyword_KeyUp);
			textSearchKeyword.Drop += new DragEventHandler(textSearchKeyword_Drop);
			textSearchKeyword.PreviewDragEnter += new DragEventHandler(textSearchKeyword_PreviewDragEnter);
			textSearchKeyword.PreviewDragOver += new DragEventHandler(textSearchKeyword_PreviewDragOver);
            searchKeywordSend.Click += new RoutedEventHandler(cmdSearchKeywordSend_MouseLeftButton_Click);
            this.KeyDown += new KeyEventHandler(MVEMain_KeyDown);
		}

        void MVEMain_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            MveClose();
        }

        void MVEMain_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.Key.ToString() == "LeftCtrl" || e.Key.ToString() == "RightCtrl")    e.Handled =true;
        }

        void cmdLogo_Click(object sender, RoutedEventArgs e)
        {
            
            
        }
        
        
        private void OpenMeetMenu(object sender, RoutedEventArgs e)
        {
            this.Meet_TopmenuItem.IsSubmenuOpen = true;
        }


		void textSearchKeyword_PreviewDragOver(object sender, DragEventArgs e)
		{
			e.Handled = true;
		}

		void textSearchKeyword_PreviewDragEnter(object sender, DragEventArgs e)
		{
			
			
			
			

			
			
		}

		void textSearchKeyword_Drop(object sender, DragEventArgs e)
		{
			string keyword = GetDraggingNodeKeyword(e);
			if (keyword == null)
				return;
			
			textSearchKeyword.Text = keyword;
			QuerySegmentByKeyword(keyword);
		}

        void cmdSearchKeywordSend_MouseLeftButton_Click(object sender, RoutedEventArgs e)
        {
            string keyword = textSearchKeyword.Text;
            if (keyword.Length > 0) QuerySegmentByKeyword(keyword);
        }

		private string GetDraggingNodeKeyword(DragEventArgs e)
		{
			XmlLinkedNode node = e.Data.GetData(STR_DND_KEYWORDITEM_FORMAT) as XmlLinkedNode;
			if (node == null || node["keyword"] == null)
				return null;
			return node["keyword"].InnerText;
		}

		void textSearchKeyword_KeyUp(object sender, KeyEventArgs e)
		{
			if (e.Key == Key.Enter)
			{
				QuerySegmentByKeyword(textSearchKeyword.Text);
			}
		}

		void MVEMain_Loaded(object sender, RoutedEventArgs e)
		{
			if (SystemParameters.FullPrimaryScreenWidth <= 1280)
			{
				
				
                this.WindowStyle = WindowStyle.SingleBorderWindow;
                this.WindowState = WindowState.Normal;
			}

            this.WindowStyle = WindowStyle.SingleBorderWindow;
            this.WindowState = WindowState.Normal;
		}

        
        void cmdCmMaximize_Click(object sender, RoutedEventArgs e)
        {
            if (this.WindowState == WindowState.Maximized)
            {
                this.WindowStyle = WindowStyle.SingleBorderWindow;
                this.WindowState = WindowState.Normal;
            }
            else
            {
                this.WindowStyle = WindowStyle.None;
                this.WindowState = WindowState.Maximized;
            }
        }

        void cmdCmCapture_Click(object sender, RoutedEventArgs e)
        {
            cmdCaptureCnvsButton_Click(sender, e);
        }

        void cmdCmExit_Click(object sender, RoutedEventArgs e)
        {
            cmdClose_Click(sender, e);
        }

		void cmdClose_Click(object sender, RoutedEventArgs e)
		{
            MveClose();
        }

        bool is_closing = false;
        void MveClose() 
        {
            if (is_closing) return;

            string message = string.Empty;
            string caption = string.Empty;
            try
            {
                //MessageBoxResult mbr = MessageBox.Show("マップを保存して終了しますか", "終了", MessageBoxButton.YesNoCancel);
                message = Application.Current.Resources["MapSavePromptMessage"] as string;
                caption = Application.Current.Resources["MapSavePromptCaption"] as string;
            }
            catch (KeyNotFoundException ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            MessageBoxResult mbr = MessageBox.Show(message, caption, MessageBoxButton.YesNoCancel);

            if (mbr == MessageBoxResult.Cancel) return;
            if (mbr == MessageBoxResult.No)
            {
                try
                {

                    base.Close();
                }
                catch (Exception e) { }
            }
            is_closing = true;
            if (WriteMappingToXaml()) 
            {
                
                try
                {
                    base.Close();
                }
                catch (Exception e) { }

            }
            else
            {
                //mbr =  MessageBox.Show("ネットワーク接続が切断されているようなので、作業を保存できません。\n それでも保存せずに終了しますか?","終了",MessageBoxButton.YesNo);
                message = (Application.Current.Resources["MapSaveErrorMessage"] as TextBlock).Text;
                caption = (Application.Current.Resources["MapSavePromptCaption"] as TextBlock).Text;
                mbr = MessageBox.Show(message, caption, MessageBoxButton.YesNo);
                if (mbr == MessageBoxResult.Yes)
                {
                    is_closing = true;
                    base.Close();
                }
                else
                {
                    message = Application.Current.Resources["NetworkWarningMessage"] as string;
                    //MessageBox.Show("保存･終了する前にネットワーク接続を確認してください", "終了");
                    MessageBox.Show(message, caption);
                    return;
                }
            }
        }

		void MainGrid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
		{
			
		}

		void MainGrid_DragLeave(object sender, DragEventArgs e)
		{
			if (overlayElement != null)
			{
				overlayElement.Visibility = Visibility.Hidden;
			}
		}

		void MainGrid_DragOver(object sender, DragEventArgs e)
		{
			if (overlayElement != null)
			{
				overlayElement.Visibility = Visibility.Visible;

				Point pt = e.GetPosition(MainGrid);
				overlayElement.LeftOffset = pt.X;
				overlayElement.TopOffset = pt.Y;
			}

		}

		#endregion 

		#region MovieList Panel Members

		
		
		
		private enum SegmentSortMode
		{
			None,
			Relation,
			Alphabetical,
            Date
		}

		private bool fSetingSortMode = false;

		
		
		
		private SegmentSortMode SortMode
		{
			get { return modeSort; }
			set 
			{
				modeSort = value;

				fSetingSortMode = true;
				if (modeSort == SegmentSortMode.Alphabetical)
					cmdSortByAlphabetical.IsChecked = true;
                else if (modeSort == SegmentSortMode.Date)
                	cmdSortByDate.IsChecked = true;
				
				
				fSetingSortMode = false;
			}
		}

		private Storyboard storyboardFullScreenMoviePlayer;
		private SegmentSortMode modeSort = SegmentSortMode.Alphabetical;
        private System.Windows.Threading.DispatcherTimer timerSelectedMovieChange = new System.Windows.Threading.DispatcherTimer();

		
		
		
		private void InitMovieListPanel()
		{
			
			
			
			
			
			
			
			

			cmdSortByAlphabetical.Checked += new RoutedEventHandler(cmdSortByAlphabetical_Checked);
			cmdSortByDate.Checked += new RoutedEventHandler(cmdSortByDate_Checked);
            

			cmdDeleteBookmark.Click += new RoutedEventHandler(cmdDeleteBookmark_Click);

			GetDataProviderFromResource(STR_SEGMENTMOVIES_PROVIDERNAME).DataChanged += new EventHandler(MVEMain_DataChanged);
			
			
			
			this.HistoryDocument = history.HistoryDocument;
            timerSelectedMovieChange.Interval = new TimeSpan(10000);
			timerSelectedMovieChange.Tick += new EventHandler(timerSelectedMovieChange_Tick);

			cmdFullScreenMoviePlayer.Click += new RoutedEventHandler(cmdFullScreenMoviePlayer_Click);
			cmdRestoreScreenMoviePlayer.Click += new RoutedEventHandler(cmdRestoreScreenMoviePlayer_Click);
			storyboardFullScreenMoviePlayer = FindResource("TimelineFullScreenMoviePlayer") as Storyboard;
			tabMovieListMode.SelectionChanged += new SelectionChangedEventHandler(tabMovieListMode_SelectionChanged);
            tabClipListMode.SelectionChanged += new SelectionChangedEventHandler(tabClipListMode_SelectionChanged);
            labelMovieHistory.MouseUp += new MouseButtonEventHandler(labelMovieHistory_MouseUp);
            listSegmentBookmark.MouseUp += new MouseButtonEventHandler(listSegmentBookmark_MouseUp);
            
        }

        void listSegmentBookmark_MouseUp(object sender, MouseButtonEventArgs e)
        {
            System.Console.WriteLine("bookmark tab");
            resultLabel.Visibility = Visibility.Hidden;

        }

        void labelMovieHistory_MouseUp(object sender, MouseButtonEventArgs e)
        {
            System.Console.WriteLine("history tab");
            resultLabel.Visibility = Visibility.Hidden;
            
        }


		void MVEMain_DataChanged(object sender, EventArgs e)
		{
			
			
			
		}

		void keyword_Click(object sender, RoutedEventArgs e)
		{
			Hyperlink link = sender as Hyperlink;
			Debug.Assert(link != null);
			XmlElement elmSelected = link.DataContext as XmlElement;
			if (elmSelected == null)
				return;
			XmlNode node = elmSelected["keyword"];
			if (node != null)
			{
				QuerySegmentByKeyword(node.InnerText);
			}
	
		}

		void cmdDeleteBookmark_Click(object sender, RoutedEventArgs e)
		{
			XmlLinkedNode node = listSegmentBookmark.SelectedItem as XmlLinkedNode;
			if (node != null && node["id"] != null && node["id"].InnerText != string.Empty)
			{
				connector.DeleteBookmark(Int32.Parse(node["id"].InnerText));
				this.BookmarkDocument = connector.QueryBookmarks();
			}
		}

		private ListBox listCurrentSegmentList = null;
        private ListBox listClipSegmentList = null;

		void tabMovieListMode_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{

            if (e.AddedItems.Count == 0)
				return;
			TabItem newItem = e.AddedItems[0] as TabItem;
			TabItem oldItem = null;
			if (e.RemovedItems.Count > 0)
				oldItem = e.RemovedItems[0] as TabItem;
			if (newItem == tabBookmark && oldItem != tabBookmark)
				this.BookmarkDocument = connector.QueryBookmarks();
                

            if (newItem == tabSearchResult)
            {
                listCurrentSegmentList = listSegmentMovies;
                resultLabel.Visibility = Visibility.Visible;

            }
            else if (newItem == tabHistory)
            {

                listCurrentSegmentList = listSegmentHistory;
                resultLabel.Visibility = Visibility.Hidden;
            }
            else if (newItem == tabBookmark){
                listCurrentSegmentList = listSegmentBookmark;
                resultLabel.Visibility = Visibility.Hidden;
            }
        }

        void tabClipListMode_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count == 0)
                return;
            TabItem newItem = e.AddedItems[0] as TabItem;
            TabItem oldItem = null;
            if (e.RemovedItems.Count > 0)
                oldItem = e.RemovedItems[0] as TabItem;
            if (newItem == tabSegmentClips)
                listClipSegmentList = listClipSegmentClips;
            else if (newItem == tabRelatedClips)
                listClipSegmentList = listRelatedSegmentClips;
        }


		private string GetSegmentNodeValue(Control ctrl, string nodename)
		{
			XmlLinkedNode node = ctrl.DataContext as XmlLinkedNode;
			Debug.Assert(node != null);
			if (node[nodename] != null)
				return node[nodename].InnerText;
			return string.Empty;
		}

		void MovieKeyword_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
		{
			TextBlock tb = sender as TextBlock;
			Debug.Assert(tb != null);
			XmlElement elmSelected = tb.DataContext as XmlElement;
			if (elmSelected == null)
				return;
			XmlNode node = elmSelected["keyword"];
			if (node != null)
			{
				QuerySegmentByKeyword(node.InnerText);
			}
		}

		void listSegmentMovies_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{

        }

        Boolean nsmp = false;
        XmlLinkedNode currentNode = null;
		void imageThumbnail_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
		{
            timerSelectedMovieChange.Stop();
            
            
            if (fMoviePlaying) StopMovie();
            currentMovie = null;
            currentNode = listSegmentMovies.SelectedItem as XmlLinkedNode;
			timerSelectedMovieChange.Start();
            nsmp = true;
        }
        /*
       
        void imageThumbnail_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
                System.Console.WriteLine("DDDD1");
                imageThumbnail_MouseLeftButtonUp(sender, e);
        }
        */
		private void SegmentSelected()
		{
			
            
            
		}

        private void UpdateCurrentClip(int id)
        {
            this.ClipSegmentsDocument = connector.Clip(id);
        }

        private void UpdateCurrentClipBySegmentId(int id)
        {
            this.ClipSegmentsDocument = connector.ClipBySegmentId(id);
        }

        private void UpdateRelatedClips(int id)
        {

            this.RelatedSegmentsDocument = connector.RelatedSegments(id);
        }

        private void SetSelectedSegmentVideo()
		{
            Debug.Assert(listCurrentSegmentList != null);
            XmlLinkedNode node = listCurrentSegmentList.SelectedItem as XmlLinkedNode;

			SetMovie(new MovieInfo(node));
		}

        private void SetSelectedSegmentVideo2()
        {
            Debug.Assert(listClipSegmentList != null);
            XmlLinkedNode node = listClipSegmentList.SelectedItem as XmlLinkedNode;
            SetMovie(new MovieInfo(node));
        }
        
        void timerSelectedMovieChange_Tick(object sender, EventArgs e)
		{
			timerSelectedMovieChange.Stop();
			SetSelectedSegmentVideo();
            if (isdc)
            {
                isdc = false;
                PlayMovie();
                
                XmlLinkedNode node = listCurrentSegmentList.SelectedItem as XmlLinkedNode;
                System.Console.WriteLine("CID:" + node["clip_id"].InnerText + " SID: " + node["id"].InnerText);
                
                
            }
		}

		void cmdSortByAlphabetical_Checked(object sender, RoutedEventArgs e)
		{
            if (fSetingSortMode)
				return;
            ChangeSortMode(SegmentSortMode.Alphabetical);
        }

        void cmdSortByDate_Checked(object sender, RoutedEventArgs e)
        {

            if (fSetingSortMode)
                return;
            ChangeSortMode(SegmentSortMode.Date);
        }

        /*
        void cmdSortByRelation_Checked(object sender, RoutedEventArgs e)
		{
			if (fSetingSortMode)
				return;
			ChangeSortMode(SegmentSortMode.Relation);
		}
        */

		private int GetCurrentSegmentIDFromIndex(int index)
		{
			if (listSegmentMovies.Items.Count <= 0)
				return -1;
			XmlLinkedNode node = listSegmentMovies.Items[index] as XmlLinkedNode;
			if (node != null && node["id"] != null)
				return Int32.Parse(node["id"].InnerText);
			return -1;
		}

		private int GetCurrentSegmentID()
		{
			XmlLinkedNode node = listSegmentMovies.SelectedItem as XmlLinkedNode;
			if (node != null && node["id"] != null)
				return Int32.Parse(node["id"].InnerText);
			return -1;
		}

		private void ChangeSortMode(SegmentSortMode newMode)
		{
			if (SortMode == newMode)
				return;
			int nCurrentSelect = GetCurrentSegmentID();

			SortMode = newMode;
            if (nCurrentSelect >= 0)
            {

                InitSortKey(nCurrentSelect);
            }
		}

		private void InitSortMode(SegmentSortMode mode)
		{
			this.SortMode = mode;
			InitSortKey(-1);
		}

		
		
		
		
		private void InitSortKey(int nKey)
		{


			ListCollectionView lcv = (ListCollectionView)(CollectionViewSource.GetDefaultView(listSegmentMovies.ItemsSource));

			if (SortMode == SegmentSortMode.Relation)
			{
				if (nKey < 0)
				{
					nKey = GetCurrentSegmentID();
					if (nKey < 0)
						return;
				}

                XmlDocument xdoc = connector.GetRelations(nKey);
				if (xdoc == null)
					return;
				Components.MVERelationSort.RelationDocument = xdoc;
				Components.MVERelationSort.NodeKey = nKey;
				RelationColorConverter.RelationDocument = xdoc;
				RelationColorConverter.NodeKey = nKey;

				
				lcv.CustomSort = new Components.MVERelationSort();

				ScrollViewer scroll = VisualTreeHelper.GetChild(listSegmentMovies, 0) as ScrollViewer;
				if (scroll != null)
					scroll.ScrollToHome();
				else
					Debug.Assert(false);

			}
			else if (SortMode == SegmentSortMode.Alphabetical)
			{
				Components.MVERelationSort.RelationDocument = null;
				Components.MVERelationSort.NodeKey = -1;
				RelationColorConverter.NodeKey = -1;

				lcv.CustomSort = new Components.MVERelationSort();

				if (nKey < 0 && listSegmentMovies.Items.Count > 0)
					listSegmentMovies.SelectedIndex = 0;
            }
            else if (SortMode == SegmentSortMode.Date)
            {
               
                Components.MVEDateSort.RelationDocument = null;
                Components.MVEDateSort.NodeKey = -1;
                lcv.CustomSort = new Components.MVEDateSort();

                if (nKey < 0 && listSegmentMovies.Items.Count > 0)
                    listSegmentMovies.SelectedIndex = 0;
               
            }
		}

		void cmdScrollUpMovies_Click(object sender, RoutedEventArgs e)
		{
			ScrollPageUpList(listSegmentMovies);
		}

		void cmdScrollDownMovies_Click(object sender, RoutedEventArgs e)
		{
			ScrollPageDownList(listSegmentMovies);
		}

		void cmdScrollUpHistoryMovies_Click(object sender, RoutedEventArgs e)
		{
			ScrollPageUpList(listSegmentHistory);
		}

		void cmdScrollDownHistoryMovies_Click(object sender, RoutedEventArgs e)
		{
			ScrollPageDownList(listSegmentHistory);
		}

		void cmdScrollUpBookmarkMovies_Click(object sender, RoutedEventArgs e)
		{
			ScrollPageUpList(listSegmentBookmark);
		}

		void cmdScrollDownBookmarkMovies_Click(object sender, RoutedEventArgs e)
		{
			ScrollPageDownList(listSegmentBookmark);
		}

		private void ScrollPageUpList(ListBox list)
		{
			ScrollViewer scroll = VisualTreeHelper.GetChild(list, 0) as ScrollViewer;
			if (scroll != null)
				scroll.PageUp();
			else
				Debug.Assert(false);
		}

		private void ScrollPageDownList(ListBox list)
		{
			ScrollViewer scroll = VisualTreeHelper.GetChild(list, 0) as ScrollViewer;
			if (scroll != null)
				scroll.PageDown();
			else
				Debug.Assert(false);
		}

		void cmdDetailScrollUp_Click(object sender, RoutedEventArgs e)
		{
			ScrollViewer scvMovieInfo = GetMovieInfoScrollViewer(sender);
			if (scvMovieInfo != null)
			{
				scvMovieInfo.LineUp();
			}
		}

		private void ScrollPageLeftList(ListBox list)
		{
			ScrollViewer scroll = VisualTreeHelper.GetChild(list, 0) as ScrollViewer;
			if (scroll != null)
				scroll.PageLeft();
			else
				Debug.Assert(false);
		}

		private void ScrollPageRightList(ListBox list)
		{
			ScrollViewer scroll = VisualTreeHelper.GetChild(list, 0) as ScrollViewer;
			if (scroll != null)
				scroll.PageRight();
			else
				Debug.Assert(false);
		}

		void cmdDetailScrollDown_Click(object sender, RoutedEventArgs e)
		{
			ScrollViewer scvMovieInfo = GetMovieInfoScrollViewer(sender);
			if (scvMovieInfo != null)
			{
				scvMovieInfo.LineDown();
			}
		}

		void scrviewDetails_ScrollChanged(object sender, ScrollChangedEventArgs e)
		{
			ScrollViewer scrViewer = sender as ScrollViewer;
			Debug.Assert(scrViewer != null);

			Grid gridParent = scrViewer.Parent as Grid;
			Debug.Assert(gridParent != null);
			foreach (UIElement elm in gridParent.Children)
			{
				Button cmd = elm as Button;
				if (cmd != null)
				{
					if (cmd.Name == "cmdDetailScrollUp")
					{
						if (scrViewer.VerticalOffset == 0)
							cmd.Visibility = Visibility.Hidden;
						else
							cmd.Visibility = Visibility.Visible;
					}
					else if (cmd.Name == "cmdDetailScrollDown")
					{
						if (scrViewer.VerticalOffset + scrViewer.ViewportHeight >= scrViewer.ExtentHeight)
							cmd.Visibility = Visibility.Hidden;
						else
							cmd.Visibility = Visibility.Visible;
					}
				}
			}
		}

		private bool fMovieItemMouseDown = false;
		private DropPreviewAdorner overlayElement = null;
		private Point ptMouseDownPos = new Point(0, 0);
		private const int N_DRAG_SPACE = 2;

        double offset;
        bool isdc = false;

		void gridMovieItem_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
		{
            if (e.ClickCount == 2)
			{
                isdc = true;
                
                
                StopMovie();
                imageThumbnail_MouseLeftButtonUp(sender, e);
                
                
                
                currentNode = listSegmentMovies.SelectedItem as XmlLinkedNode;
            }
            
			Grid gridItem = sender as Grid;
			Debug.Assert(gridItem != null);
			ptMouseDownPos = e.GetPosition(this);
			fMovieItemMouseDown = true;
        }

		void gridMovieItem_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
		{

			fMovieItemMouseDown = false;
            ptMouseDownPos = new Point(0, 0);
            
        }

		private AdornerLayer draggingLayer;
		void gridMovieItem_MouseMove(object sender, MouseEventArgs e)
		{
			Grid gridItem = sender as Grid;
			Point ptCurPos = e.GetPosition(this);
			if (fMovieItemMouseDown
				&& ( ptCurPos.X < ptMouseDownPos.X - N_DRAG_SPACE || ptCurPos.X > ptMouseDownPos.X + N_DRAG_SPACE || ptCurPos.Y < ptMouseDownPos.Y - N_DRAG_SPACE || ptCurPos.Y > ptMouseDownPos.Y + N_DRAG_SPACE))
			{
				
				e.Handled = true;
				fMovieItemMouseDown = false;
				XmlLinkedNode node = gridItem.DataContext as XmlLinkedNode;
				if (node == null)
				{
					return;
				}
				DataObject data = new DataObject();
				data.SetData(STR_DND_MOVIEITEM_FORMAT, node);

				Image imgDragPreview = null;
				if (node["thumb_url"] != null)
				{
					string thumbnail_url = node["thumb_url"].InnerText;
					Image imgThumbnail = GetMovieImageFromListItem(sender);
					if (imgThumbnail == null || string.IsNullOrEmpty(thumbnail_url))
					{
						return;
					}

					imgDragPreview = new Image();
					imgDragPreview.Source = imgThumbnail.Source;
					imgDragPreview.Width = 80;
					imgDragPreview.Height = 60;
					imgDragPreview.Tag = node;

					
					imgDragPreview.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
					imgDragPreview.Arrange(new Rect(new Size(imgDragPreview.Width, imgDragPreview.Height)));

					overlayElement = new DropPreviewAdorner((UIElement)MainGrid, imgDragPreview);
					if (draggingLayer == null)
						draggingLayer = AdornerLayer.GetAdornerLayer(MainGrid);
					draggingLayer.Add(overlayElement);
				}
				DragDrop.DoDragDrop(gridItem, data, DragDropEffects.Copy);

				if (imgDragPreview != null)
				{
					imgDragPreview = null;
					draggingLayer.Remove(overlayElement);
					overlayElement = null;
				}
			}

		}


        void gridSegmentMovieItem_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        { }

        void gridSegmentMovieItem_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        { }

        void gridSegmentMovieItem_MouseMove(object sender, MouseEventArgs e)
        { }

        void gridSegmentMovieItem_Drop(object sender, DragEventArgs e)
        { }


        void gridRelatedMovieItem_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

        }

        void gridRelatedMovieItem_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            SetSelectedSegmentVideo2();
        }

        void gridRelatedMovieItem_MouseMove(object sender, MouseEventArgs e)
        { 
            
        
        }

        void gridRelatedMovieItem_Drop(object sender, DragEventArgs e)
        { }
        

        private ScrollViewer GetMovieInfoScrollViewer(object sender)
		{
			Button cmd = sender as Button;
			Grid gridParent = cmd.Parent as Grid;
			UIElement elm = FindElement(gridParent.Children, "scrviewDetails");
			if (elm != null)
				return elm as ScrollViewer;
			return null;
		}

		private Image GetMovieImageFromListItem(object sender)
		{
			Grid item = sender as Grid;
			foreach (UIElement elm in item.Children)
			{
				if (elm.GetType() == typeof(System.Windows.Controls.Image))
				{
					return elm as Image;
				}
			}
			return null;
		}

		void cmdAddBookmark_Click(object sender, RoutedEventArgs e)
		{
			Button btn = sender as Button;
			Debug.Assert(btn != null);

			string strSegmentId = GetSegmentNodeValue(btn, "id");
			Debug.Assert(strSegmentId != string.Empty);
			connector.AddBookmark(Int32.Parse(strSegmentId));

			StackPanel panel = btn.Content as StackPanel;
			
			
			

		}

		void gridMovieItem_Drop(object sender, DragEventArgs e)
		{
			string keyword = GetDraggingNodeKeyword(e);
			if (keyword == null)
				return;

			Button btn = GetAddKeywordButtonFromListItem(sender);
			string strSegmentId = GetSegmentNodeValue(btn, "id");
			if (btn != null && !string.IsNullOrEmpty(strSegmentId))
				AddSegmentKeyword(btn, Int32.Parse(strSegmentId), keyword);
		}

		void cmdAddMovieKeyword_Click(object sender, RoutedEventArgs e)
		{
			Button btn = sender as Button;
			Debug.Assert(btn != null);

			XmlLinkedNode node = btn.DataContext as XmlLinkedNode;
			Debug.Assert(node != null);

			int idSegment = Int32.Parse(node["id"].InnerText);
			AddSegmentKeyword(btn, idSegment, string.Empty);
		}

		private Button GetAddKeywordButtonFromListItem(object sender)
		{
			Grid item = sender as Grid;
			Debug.Assert(item != null);

			UIElement elmScrollViewer = FindElement(item.Children, "scrviewDetails");
			if (elmScrollViewer != null)
			{
				ScrollViewer viewer = elmScrollViewer as ScrollViewer;
				StackPanel vpanel = viewer.Content as StackPanel;
				if (vpanel != null)
				{
					UIElement elmHPanel = FindElement(vpanel.Children, "spanelDetailFooter");
					if (elmHPanel != null)
					{
						StackPanel hpanel = elmHPanel as StackPanel;
						UIElement elmAddButton = FindElement(hpanel.Children, "cmdAddMovieKeyword");
						if (elmAddButton != null)
						{
							return elmAddButton as Button;
						}
					}
				}
			}
			return null;

		}

		private UIElement FindElement(UIElementCollection items, string name)
		{
			foreach (UIElement elm in items)
			{
				Control ctrl = elm as Control;
				if (ctrl != null && ctrl.Name == name)
					return elm;
				Panel panel = elm as Panel;
				if (panel != null && panel.Name == name)
					return elm;
				FrameworkElement felm = elm as FrameworkElement;
				if (felm != null && felm.Name == name)
					return elm;
			}
			return null;
		}

		private void AddSegmentKeyword(Button btnAdd, int idSegment, string keyword)
		{
			

			

			

			
			
			
			
			
			
			
			

			
			
			
		}
        /*
		private System.Windows.Controls.Primitives.Popup GetAddKeywordPopupFromChild(object sender)
		{
			Control ctrl = sender as Control;
			return ctrl.Parent as System.Windows.Controls.Primitives.Popup;
		}
        */

		
		
		
		
		
		
		
		
		
		
		
		
		
			
		
		
		
		

		
		
		
		
		
		

		#endregion

		#region Mapping Panel Members

		private Shapes.ShapeManager shapeManager = new MVExplorer.Shapes.ShapeManager();
		private bool fMappingDrawing = false;
		Point ptMouseStart;
		Shape elDragging;
		ColorPicker colorPicker = new ColorPicker();

		private System.Windows.Threading.DispatcherTimer timerActivateTextBox = new System.Windows.Threading.DispatcherTimer();
		private System.Windows.Threading.DispatcherTimer timerMappingAutoSave = new System.Windows.Threading.DispatcherTimer();

		private TextBox tbNew = null;

		
		
		

		
		
		
		private void InitMappingPanel()
		{
			inkCnvsMapping.EditingMode = InkCanvasEditingMode.None;

			
			inkCnvsMapping.Drop += new DragEventHandler(inkCnvsMapping_Drop);

			
			inkCnvsMapping.MouseLeftButtonDown += new MouseButtonEventHandler(inkCnvsMapping_MouseLeftButtonDown);
			inkCnvsMapping.MouseRightButtonDown += new MouseButtonEventHandler(inkCnvsMapping_MouseRightButtonDown);
			inkCnvsMapping.MouseUp += new MouseButtonEventHandler(inkCnvsMapping_MouseUp);
			inkCnvsMapping.MouseMove += new MouseEventHandler(inkCnvsMapping_MouseMove);

			
            cmdCnvsPrevButton.Click += new RoutedEventHandler(cmdCnvsPrevButton_Click);
            cmdCnvsNextButton.Click += new RoutedEventHandler(cmdCnvsNextButton_Click);
            cmdAddCnvsButton.Click += new RoutedEventHandler(cmdAddCnvsButton_Click);
            cmdDelCnvsButton.Click += new RoutedEventHandler(cmdDelCnvsButton_Click);
            

            

			cmdCnvsModeCircle.Click += new RoutedEventHandler(cmdCnvsModeCircle_Click);
			cmdCnvsModeRectangle.Click += new RoutedEventHandler(cmdCnvsModeRectangle_Click);
			cmdCnvsModeArrow.Click += new RoutedEventHandler(cmdCnvsModeArrow_Click);
            

			cmdCnvsModeText.Click += new RoutedEventHandler(cmdCnvsModeText_Click);
			cmdCnvsModeSelect.Click += new RoutedEventHandler(cmdCnvsModeSelect_Click);
			cmdCnvsDeleteShape.Click += new RoutedEventHandler(cmdCnvsDeleteShape_Click);
			cmdColorSelector.Click += new RoutedEventHandler(cmdColorSelector_Click);
			cmdFullScreenMapping.Click += new RoutedEventHandler(cmdFullScreenMapping_Click);
			cmdRestoreScreenMapping.Click += new RoutedEventHandler(cmdRestoreScreenMapping_Click);

            cmdCnvsTextUp.Click += new RoutedEventHandler(cmdTextUp_Click);
            cmdCnvsTextDown.Click += new RoutedEventHandler(cmdTextDown_Click);
            cmdCnvsUndo.Click += new RoutedEventHandler(cmdCnvsUndo_Click);
            cmdCnvsRedo.Click += new RoutedEventHandler(cmdCnvsRedo_Click);
    
			ColorPickerPopper.Child = colorPicker;
			colorPicker.Picked += new EventHandler(colorPicker_Picked);
			colorPicker.Canceled += new EventHandler(colorPicker_Canceled);

			storyboardFullScreenMapping = FindResource("TimelineFullScreenMapping") as Storyboard;
			timerActivateTextBox.Tick += new EventHandler(timerActivateTextBox_Tick);
			timerActivateTextBox.Interval = new TimeSpan(10000);

			timerMappingAutoSave.Tick += new EventHandler(timerMappingAutoSave_Tick);
			timerMappingAutoSave.Interval = new TimeSpan(90 * 1000 * 1000 * 10); 

            shapeManager.Mode = MVExplorer.Shapes.DrawingMode.None;
            inkCnvsMapping.EditingMode = InkCanvasEditingMode.Select;
		}

		void timerMappingAutoSave_Tick(object sender, EventArgs e)
		{
			timerMappingAutoSave.Stop();
			Debug.WriteLine("Save Mapping");
			WriteMappingToXaml();
		}

		void timerActivateTextBox_Tick(object sender, EventArgs e)
		{
			timerActivateTextBox.Stop();
			if (tbNew == null)
				return;
			tbNew.Focus();
			tbNew.SelectAll();
			Shapes.ShapeText.UpdateTextBoxRect(tbNew);
		}

		private bool fFullScreenMapping = false;
		private Storyboard storyboardFullScreenMapping;

		void cmdFullScreenMapping_Click(object sender, RoutedEventArgs e)
		{
			ToggleMappingFullscreenMode();
		}

        void cmdCnvsPrevButton_Click(object sender, RoutedEventArgs e) {
            Debug.WriteLine("prev" + mapPage);
            if (mapPage > 1){
                mapPage--;
                revertCanvas(mapPage+1);
                setCanvas(mapPage);
            }
            cnvsNumberLabel.Content = mapPage + " / " + canvass.Count;
        }

        void cmdCnvsNextButton_Click(object sender, RoutedEventArgs e) {
            Debug.WriteLine("next" + mapPage);
            if (mapPage < canvass.Count)
            {
                mapPage++;
                revertCanvas(mapPage -1);
                setCanvas(mapPage);
            }
            cnvsNumberLabel.Content = mapPage + " / " + canvass.Count;
        }

        void cmdAddCnvsButton_Click(object sender, RoutedEventArgs e)
        {
            List<MapDrawing> tlist = new List<MapDrawing>();

            for(int i=0;i<mapPage;i++) tlist.Add(canvass[i]);
            tlist.Add(new MapDrawing());
            if (mapPage < canvass.Count)
            {
                for (int i = mapPage; i < canvass.Count; i++) tlist.Add(canvass[i]);
            }
            canvass = tlist;
            cmdCnvsNextButton_Click(sender,e);
   
        }

        void cmdDelCnvsButton_Click(object sender, RoutedEventArgs e)
        {
            if (canvass.Count < 2) return;

            
            //System.Windows.Forms.DialogResult result;
            string messageFormat = Application.Current.Resources["EliminateSlideMessage"] as string;
            string message = string.Format(messageFormat, mapPage.ToString());
            string caption = Application.Current.Resources["EliminateSlideCaption"] as string;
            MessageBoxResult result = MessageBox.Show(message, caption, MessageBoxButton.YesNo);
            //result = (System.Windows.Forms.DialogResult) MessageBox.Show("本当に"+mapPage+"枚目のスライドを削除しますか？", "スライドの削除", MessageBoxButton.YesNo);
 
            if(result == MessageBoxResult.No)
            {
                return;
            }
            canvass.RemoveAt(mapPage-1);
            if (mapPage > 1)
            {
                mapPage--;
            }
            setCanvas(mapPage);
            cnvsNumberLabel.Content = mapPage + " / " + canvass.Count;

            
        }

        bool is_full = true;
        void cmdCaptureCnvsButton_Click(object sender, RoutedEventArgs e)
        {

            
                resultLabel.Visibility = Visibility.Hidden;

            is_full = (this.WindowState == WindowState.Maximized);
            if (!is_full)
            {
                this.WindowStyle = WindowStyle.None;
                this.WindowState = WindowState.Maximized;
            }

            Storyboard story = FindResource("CaptureMapping") as Storyboard;
            story.Completed += new EventHandler(captureMap);
            this.BeginStoryboard(story);

            
            


        }

        void cmdCaptureCnvsButton_Click2(object sender, RoutedEventArgs e)
        {
            WriteMappingToXaml();
        }

        void captureMap(object sender, EventArgs e)
        {
            DateTime now = DateTime.Now;
            String filename = "MVE" + now.ToString("yyyyMMddHHmmss") + ".png";
            ScreenCapture.capture(filename);

            Storyboard shrink = FindResource("TimelineShrinkMapping") as Storyboard;
            if (!is_full) shrink.Completed += new EventHandler(normalizeWindow);
            this.BeginStoryboard(shrink);


        }
        void normalizeWindow(object sender, EventArgs e)
        {
            this.WindowState = WindowState.Normal;
            this.WindowStyle = WindowStyle.SingleBorderWindow;
            resultLabel.Visibility = Visibility.Visible;

        }



        void cmdRestoreScreenMapping_Click(object sender, RoutedEventArgs e)
		{
			ToggleMappingFullscreenMode();
		}

		private void ToggleMappingFullscreenMode()
		{
			if (!fFullScreenMapping)
			{
                resultLabel.Visibility = Visibility.Hidden;
                cmdFullScreenMapping.Visibility = Visibility.Hidden;
				cmdRestoreScreenMapping.Visibility = Visibility.Visible;
				this.BeginStoryboard(storyboardFullScreenMapping);
				fFullScreenMapping = true;
			}
			else
			{
                resultLabel.Visibility = Visibility.Visible;
                cmdRestoreScreenMapping.Visibility = Visibility.Hidden;
				cmdFullScreenMapping.Visibility = Visibility.Visible;
				Storyboard storyboardShrinkMapping = FindResource("TimelineShrinkMapping") as Storyboard;
				this.BeginStoryboard(storyboardShrinkMapping);
				fFullScreenMapping = false;
            }
		}

		private const string STR_BASE64_HEAD = "base64:";
		private bool WriteMappingToXaml()
		{
			
			
            XmlDocument savexml = new XmlDocument();
            XmlElement canvasElement = savexml.CreateElement("canvas");
            String icXaml ="";

            revertCanvas(mapPage);

            MapDrawing origialMd = canvass[mapPage-1];
            inkCnvsMapping.Children.Clear();

            foreach(MapDrawing page in canvass){
                InkCanvas   ic = new InkCanvas();
                /*
                ic.MinHeight=10;
                ic.MinWidth=10;
                ic.Margin = new Thickness(10, 10, 35, 10);
                ic.EditingMode = InkCanvasEditingMode.None;
                ic.MoveEnabled = true;
                ic.Name="inkCnvsMapping";
                ic.ResizeEnabled = true;
                ic.AllowDrop= true;
                ic.Opacity=1;
                */
                foreach(UIElement elm in page.Elements){
                    inkCnvsMapping.Children.Remove(elm);
                    ic.Children.Add(elm);
                }

                for(int i=0;i<ic.Children.Count;i++){
                    UIElement elm = ic.Children[i];
                    FrameworkElement ctrl = elm as FrameworkElement;
                    if (ctrl == null)
                        continue;

                    MovieInfo info = ctrl.Tag as MovieInfo;
                    if (info == null)
                        continue;

                    BinaryFormatter formatter = new BinaryFormatter();

                    using (MemoryStream stm = new MemoryStream())
                    {
                        formatter.Serialize(stm, info);
                        byte[] b = stm.ToArray();

                        ctrl.Tag = STR_BASE64_HEAD + Convert.ToBase64String(b);
                        stm.Close();
                    }
                }

                using (MemoryStream ms = new MemoryStream())
                {
                    System.Windows.Markup.XamlWriter.Save(ic, ms);
                    ms.Seek(0, SeekOrigin.Begin);
                    using (StreamReader sr = new StreamReader(ms))
                    {
                        string strXaml = sr.ReadToEnd();
                        
                        icXaml += strXaml;
                    }
                }
                canvasElement.InnerXml = icXaml;
                ic.Children.Clear();
            }
            savexml.AppendChild(canvasElement);

            bool ret = false;

            using (MemoryStream ms = new MemoryStream())
            {
                System.Windows.Markup.XamlWriter.Save(inkCnvsMapping, ms);
                ms.Seek(0, SeekOrigin.Begin);
                using (StreamReader sr = new StreamReader(ms))
                {
                    string strXaml = sr.ReadToEnd();
                    
                   if(connector != null)   ret = connector.SaveMap(savexml.OuterXml);

                }
            }

            /*
			foreach (UIElement elm in inkCnvsMapping.Children)
			{
				FrameworkElement ctrl = elm as FrameworkElement;
				if (ctrl == null)
					continue;
				MovieInfo info = ctrl.Tag as MovieInfo;
				if (info == null)
					continue;
				BinaryFormatter formatter = new BinaryFormatter();
				using(MemoryStream stm = new MemoryStream())
				{
					formatter.Serialize(stm, info);
					byte[] b = stm.ToArray();
					ctrl.Tag = STR_BASE64_HEAD + Convert.ToBase64String(b);
					stm.Close();
				}
			}

			using (MemoryStream ms = new MemoryStream())
			{
				System.Windows.Markup.XamlWriter.Save(inkCnvsMapping, ms);
				ms.Seek(0, SeekOrigin.Begin);
				using (StreamReader sr = new StreamReader(ms))
				{
					string strXaml = sr.ReadToEnd();
					if(connector != null)   connector.SaveMap(strXaml);
				}
			}
            */
            

            /*
			using (FileStream fs = new FileStream("c:\\MVE.xaml", FileMode.Create))
			{
			    System.Windows.Markup.XamlWriter.Save(inkCnvsMapping, fs);
			}
             */

            /*
            Debug.WriteLine(savexml.OuterXml);
            */

            inkCnvsMapping.Children.Clear();
            foreach (UIElement elm in origialMd.Elements)
            {
                    decodeUIElement(elm);
                inkCnvsMapping.Children.Add(elm);
            }
            return ret;
		}

        private UIElement decodeUIElement(UIElement elm)
        {
            FrameworkElement ctrl = elm as FrameworkElement;
            
            if (ctrl != null)
            {
                string strTag = ctrl.Tag as string;

                if (strTag != null && strTag.StartsWith(STR_BASE64_HEAD))
                {
                    strTag = strTag.Replace(" ", "+");

                    byte[] b = Convert.FromBase64String(strTag.Substring(STR_BASE64_HEAD.Length));
                    using (MemoryStream stm = new MemoryStream(b))
                    {
                        BinaryFormatter formatter = new BinaryFormatter();
                        ctrl.Tag = formatter.Deserialize(stm);
                    }
                }
            }
            return ctrl;
        }


		private void ReadMappingFromXaml()
		{
			Debug.Assert(connector != null);

			string strXamlMap = connector.LoadMap();
            if (string.IsNullOrEmpty(strXamlMap))
            {
                canvass.Add(new MapDrawing());
                setCanvas(mapPage);
                cnvsNumberLabel.Content = mapPage + " / " + canvass.Count;
                return;
            }
            try
			{
                XmlDocument xd = new XmlDocument();
                xd.LoadXml(strXamlMap);
                XmlNodeList list = xd.SelectSingleNode("/canvas").ChildNodes;
                

                if (list.Count < 1)
                {
                    canvass.Add(new MapDrawing());
                    setCanvas(mapPage);
                    cnvsNumberLabel.Content = mapPage + " / " + canvass.Count;
                    return;
                }

                foreach (XmlNode node in list)
                {
                    String str = node.OuterXml;

                    using (XmlTextReader xr = new XmlTextReader(new StringReader(str)))
                    {
                        object obj = System.Windows.Markup.XamlReader.Load(xr);
                        InkCanvas cnvsLoaded = obj as InkCanvas;

                        MapDrawing md = new MapDrawing();
                        List<UIElement> elms = new List<UIElement>(cnvsLoaded.Children.Count);

                        if (cnvsLoaded != null)
                        {

                            for (int i = cnvsLoaded.Children.Count; i > 0; i--)
                            {
                                UIElement elm = cnvsLoaded.Children[i - 1];
                                FrameworkElement ctrl = elm as FrameworkElement;
                                
                                if (ctrl != null)
                                {
                                    string strTag = ctrl.Tag as string;

                                    if (strTag != null && strTag.StartsWith(STR_BASE64_HEAD))
                                    {
                                        strTag = strTag.Replace(" ", "+");

                                        byte[] b = Convert.FromBase64String(strTag.Substring(STR_BASE64_HEAD.Length));
                                        using (MemoryStream stm = new MemoryStream(b))
                                        {
                                            BinaryFormatter formatter = new BinaryFormatter();
                                            ctrl.Tag = formatter.Deserialize(stm);
                                        }
                                    }
                                    TextBox tb = ctrl as TextBox;
                                    if (tb != null)
                                        SetElementToTextBox(tb);
                                }
                                cnvsLoaded.Children.Remove(elm);
                                elms.Add(elm);
                            }
                            md.Elements = elms;
                            canvass.Add(md);
                        }

                    }
                }

                if (canvass.Count < 1) canvass.Add(new MapDrawing() );
                setCanvas(mapPage);
                cnvsNumberLabel.Content = mapPage + " / " + canvass.Count;

                /*
                using (XmlTextReader xr = new XmlTextReader(new StringReader(strXamlMap)))
				{

                    canvass = new List<MapDrawing>();




                    object obj = System.Windows.Markup.XamlReader.Load(xr);
					InkCanvas cnvsLoaded = obj as InkCanvas;

                    



                        MapDrawing md = new MapDrawing();
                        List<UIElement> elms = new List<UIElement>();

                        if (cnvsLoaded != null)
                        {

                            for (int i = cnvsLoaded.Children.Count; i > 0; i--)
                            {
                                UIElement elm = cnvsLoaded.Children[0];
                                FrameworkElement ctrl = elm as FrameworkElement;
                                
                                if (ctrl != null)
                                {
                                    string strTag = ctrl.Tag as string;
                                    if (strTag != null && strTag.StartsWith(STR_BASE64_HEAD))
                                    {
                                        byte[] b = Convert.FromBase64String(strTag.Substring(STR_BASE64_HEAD.Length));
                                        using (MemoryStream stm = new MemoryStream(b))
                                        {
                                            BinaryFormatter formatter = new BinaryFormatter();
                                            ctrl.Tag = formatter.Deserialize(stm);
                                        }
                                    }
                                    TextBox tb = ctrl as TextBox;
                                    if (tb != null)
                                        SetElementToTextBox(tb);
                                }
                                cnvsLoaded.Children.Remove(elm);
                                elms.Add(elm);
                                
                            }

                            md.Elements = elms;

                            
                            TextBox tb1 = new TextBox();
                            tb1.Width = 100;
                            tb1.Height = 20;
                            tb1.Text = "slide1";
                            MapDrawing md1 = new MapDrawing();
                            md.Add(tb1);

                            canvass.Add(md);
                        }




				}
                */
			}
			catch (Exception ex)
			{
				Debug.Assert(false, ex.Message);
			}

			
			
			
			
			
		}

        void setCanvas(int page){

            MapDrawing md = canvass[page - 1];

            inkCnvsMapping.Children.Clear();
            
            foreach(UIElement elm in md.Elements){
                decodeUIElement(elm);
                inkCnvsMapping.Children.Add(elm);
            }
        }

        void revertCanvas(int page){

            List<UIElement> elms = new List<UIElement>();
            MapDrawing omd = new MapDrawing();
            for (int i = 0; i < inkCnvsMapping.Children.Count; i++)
            {
                UIElement e = inkCnvsMapping.Children[i];
                omd.Add(inkCnvsMapping.Children[i]);
            }

            canvass[page - 1] = omd;
            for (int i = inkCnvsMapping.Children.Count-1; i >= 0; i--)
            {
                UIElement e = inkCnvsMapping.Children[i];
                inkCnvsMapping.Children.Remove(e);
            }

        }

        void colorPicker_Picked(object sender, EventArgs e)
		{
			rectCurrentColor.Fill = colorPicker.PickedBrush;

            
            System.Collections.ObjectModel.ReadOnlyCollection<UIElement> elmsSelected = inkCnvsMapping.GetSelectedElements();
            if (elmsSelected.Count > 0)
            {
                for (int i = 0; i < elmsSelected.Count; i++)
                {
                    if (elmsSelected[i] is Shape)
                    {
                        ((Shape)elmsSelected[i]).Stroke = colorPicker.PickedBrush;
                    }
                    else if (elmsSelected[i] is TextBox)
                    {
                        ((TextBox)elmsSelected[i]).Foreground = colorPicker.PickedBrush;
                    }
                    
                    
                }
            }

            ColorPickerPopper.IsOpen = false;

		}

		void colorPicker_Canceled(object sender, EventArgs e)
		{
			ColorPickerPopper.IsOpen = false;
		}

		void cmdColorSelector_Click(object sender, RoutedEventArgs e)
		{
			ColorPickerPopper.IsOpen = !ColorPickerPopper.IsOpen;
		}

		void cmdCnvsModeSelect_Click(object sender, RoutedEventArgs e)
		{
			shapeManager.Mode = MVExplorer.Shapes.DrawingMode.None;
			inkCnvsMapping.EditingMode = InkCanvasEditingMode.Select;
		}

		void cmdCnvsDeleteShape_Click(object sender, RoutedEventArgs e)
		{
			System.Collections.ObjectModel.ReadOnlyCollection<UIElement> elmsSelected = inkCnvsMapping.GetSelectedElements();
			if (elmsSelected.Count > 0)
			{
				for (int i = 0; i < elmsSelected.Count; i++)
				{
					inkCnvsMapping.Children.Remove(elmsSelected[i]);
				}
			}
		}

		void inkCnvsMapping_Drop(object sender, DragEventArgs e)
		{
			string keyword = GetDraggingNodeKeyword(e);
			if (!string.IsNullOrEmpty(keyword))
			{
				AddTextElementToMappingCanvas(keyword, e.GetPosition(inkCnvsMapping));
				return;
			}
			XmlLinkedNode node = e.Data.GetData(STR_DND_MOVIEITEM_FORMAT) as XmlLinkedNode;
			if (node == null)
				return;
			string thumbnail_url = node["thumb_url"].InnerText;
			if (string.IsNullOrEmpty(thumbnail_url))
				return;

			Image img = new Image();
			BitmapImage bi = new BitmapImage(new Uri(thumbnail_url));
			img.Source = bi;
			img.Width = 80;
			img.Height = 60;
			
			
			
			img.Tag = new MovieInfo(node);
            System.Console.WriteLine("MoVIEINFO" + node.OuterXml);
			inkCnvsMapping.Children.Add(img);
			Point pt = e.GetPosition(inkCnvsMapping);
			InkCanvas.SetLeft(img, pt.X);
			InkCanvas.SetTop(img, pt.Y);
			e.Handled = true;
		}

		void cmdCnvsModeRectangle_Click(object sender, RoutedEventArgs e)
		{
			SetCanvasDrawingMode(inkCnvsMapping);
			shapeManager.Mode = MVExplorer.Shapes.DrawingMode.Rectangle;
		}

		void cmdCnvsModeCircle_Click(object sender, RoutedEventArgs e)
		{
			SetCanvasDrawingMode(inkCnvsMapping);
			shapeManager.Mode = MVExplorer.Shapes.DrawingMode.Circle;
		}

		void cmdCnvsModeArrow_Click(object sender, RoutedEventArgs e)
		{
			SetCanvasDrawingMode(inkCnvsMapping);
			shapeManager.Mode = MVExplorer.Shapes.DrawingMode.Arrow;
		}

        void cmdCnvsModeLine_Click(object sender, RoutedEventArgs e)
        {
            SetCanvasDrawingMode(inkCnvsMapping);
            shapeManager.Mode = MVExplorer.Shapes.DrawingMode.Line;
        }
        
        void cmdCnvsModeText_Click(object sender, RoutedEventArgs e)
		{
			SetCanvasDrawingMode(inkCnvsMapping);
			shapeManager.Mode = MVExplorer.Shapes.DrawingMode.Text;
			inkCnvsMapping.Cursor = Cursors.IBeam;
		}


        void cmdTextUp_Click(object sender, RoutedEventArgs e)
        {
            System.Collections.ObjectModel.ReadOnlyCollection<UIElement> elmsSelected = inkCnvsMapping.GetSelectedElements();
            if (elmsSelected.Count > 0)
            {
                for (int i = 0; i < elmsSelected.Count; i++)
                {
                    if (elmsSelected[i] is TextBox)
                    {
                        double fs = ((TextBox)elmsSelected[i]).FontSize;
                        ((TextBox)elmsSelected[i]).FontSize = fs + 2;
                    }
                    
                    
                }
            }

        }

        void cmdTextDown_Click(object sender, RoutedEventArgs e)
        {
            System.Collections.ObjectModel.ReadOnlyCollection<UIElement> elmsSelected = inkCnvsMapping.GetSelectedElements();
            if (elmsSelected.Count > 0)
            {
                for (int i = 0; i < elmsSelected.Count; i++)
                {
                    if (elmsSelected[i] is TextBox)
                    {
                        double fs = ((TextBox)elmsSelected[i]).FontSize;
                        ((TextBox)elmsSelected[i]).FontSize = fs - 2;
                    }
                    
                    
                }
            }


        }

        void cmdCnvsUndo_Click(object sender, RoutedEventArgs e)
        {
            if (drawingUndoStack.Count > 0)
            {
                List<MapDrawing> cvss = drawingUndoStack.Pop();
                if (cvss != null)
                {
                    addToRedoStack();
                    this.canvass = cvss;
                    setCanvas(mapPage);
                }
            }
        }


        void cmdCnvsRedo_Click(object sender, RoutedEventArgs e)
        {
            if (drawingRedoStack.Count > 0)
            {

                List<MapDrawing> cvss = drawingRedoStack.Pop();
                if (cvss != null)
                {
                    this.canvass = cvss;
                    setCanvas(mapPage);
                    drawingUndoStack.Push(cvss);
                }
            }
        }
        
        
        bool SetCanvasDrawingMode(InkCanvas canvas)
		{
			if (canvas.EditingMode == InkCanvasEditingMode.Select)
			{
				canvas.EditingMode = InkCanvasEditingMode.None;
				return true;
			}
			else
				return false;
		}

		private Shape GetPointShape(Point ptMouse)
		{
			return inkCnvsMapping.InputHitTest(ptMouse) as Shape;
		}

		private UIElement GetPointUIElement(Point ptMouse)
		{
			return inkCnvsMapping.InputHitTest(ptMouse) as UIElement;
		}

		void inkCnvsMapping_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
		{
			if (fMappingDrawing)
				return;

            
            addToUndoStack();

			
			Mouse.Capture(inkCnvsMapping, CaptureMode.SubTree);

			elDragging = shapeManager.NewShape();
			AddDrawingElementToMappingCanvas(elDragging);
			ptMouseStart = e.GetPosition(inkCnvsMapping);
			InkCanvas.SetLeft(elDragging, ptMouseStart.X);
			InkCanvas.SetTop(elDragging, ptMouseStart.Y);

			e.Handled = true;

		}

		void inkCnvsMapping_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
		{
            Point ptMouse = e.GetPosition(inkCnvsMapping);
            Shape elSelected = GetPointShape(ptMouse);
            Image imgSelected = GetPointUIElement(ptMouse) as Image;
            if (elSelected != null)
            {
                inkCnvsMapping.EditingMode = InkCanvasEditingMode.Select;
                inkCnvsMapping.Select(new FrameworkElement[] { elSelected });
                return;
            }
            else if (imgSelected != null)
            {
                MovieInfo info = imgSelected.Tag as MovieInfo;
                if (info != null)
                    
                    this.UpdateCurrentClip(info.idSegment);
                    SetMovie(info);
            }
		}


        List<MapDrawing> cloneCanvass()
        {
            List<MapDrawing> cc = new List<MapDrawing>(canvass.Count);
            for (int i = 0; i < canvass.Count; i++)
            {
                cc.Add(canvass[i].clone());
            }
            return cc;
        }

        void addToUndoStack()
        {
            revertCanvas(mapPage);
            List<MapDrawing> cc = cloneCanvass();
            drawingUndoStack.Push(cc);
            drawingRedoStack.Clear();
            setCanvas(mapPage);

        }
        void addToRedoStack()
        {
            revertCanvas(mapPage);
            List<MapDrawing> cc = cloneCanvass();
            drawingRedoStack.Push(cc);
            setCanvas(mapPage);

        }


		void inkCnvsMapping_MouseUp(object sender, MouseButtonEventArgs e)
		{
            Point ptMouse = e.GetPosition(inkCnvsMapping);
			if (e.ChangedButton == MouseButton.Left)
			{
				timerMappingAutoSave.Start();
                
                
                if (fMappingDrawing)
				{
                    

                    UIElement elmResult = shapeManager.GenerateResult(elDragging);
					
					
					if (elmResult != null)
					{
						inkCnvsMapping.Children.Remove(elDragging);
						AddDrawingElementToMappingCanvas(elmResult);
						InkCanvas.SetLeft(elmResult, Math.Min(ptMouseStart.X, ptMouse.X));
						InkCanvas.SetTop(elmResult, Math.Min(ptMouseStart.Y, ptMouse.Y));

                    }
					else 
					{
						elDragging.Stroke = colorPicker.PickedBrush;
						elDragging.StrokeThickness = 2;
						
					}
					
					elDragging = null;
					fMappingDrawing = false;
					Mouse.Capture(null);

				}
				else
				{
					if (elDragging != null)
					{
						inkCnvsMapping.Children.Remove(elDragging);
						Mouse.Capture(null);
						elDragging = null;
					}
					if (shapeManager.Mode == MVExplorer.Shapes.DrawingMode.Text)
					{
						tbNew = AddTextElementToMappingCanvas(string.Empty, ptMouse);
						if (tbNew != null)
						{
							timerActivateTextBox.Start();
							return;
						}
					}
					if (ptMouse == ptMouseStart)
					{
						Shape elSelected = GetPointShape(ptMouse);
						Image imgSelected = GetPointUIElement(ptMouse) as Image;
						if (elSelected != null)
						{
							inkCnvsMapping.EditingMode = InkCanvasEditingMode.Select;
							inkCnvsMapping.Select(new FrameworkElement[] { elSelected });
							return;
						}
						else if (imgSelected != null)
						{
                            
							MovieInfo info = imgSelected.Tag as MovieInfo;
                            if (info != null)
                                setMovieFromMapping(info);
								
						}
					}
				}
			}
			else if(e.ChangedButton == MouseButton.Right)
			{

			}
			else
			{
			}
		}

        MovieInfo theMovieInfo = null;
        bool presentationMode = false;
        EventHandler evh = null;
        Storyboard storyboardShrinkMapping;
        void setMovieFromMapping(MovieInfo info)
        {
            if (fFullScreenMapping)
            {
                theMovieInfo = info;
                presentationMode = true;
                cmdRestoreScreenMoviePlayer.Visibility = Visibility.Hidden;
                cmdFullScreenMoviePlayer.Visibility = Visibility.Visible;
                storyboardShrinkMapping = FindResource("TimelineShrinkMapping") as Storyboard;
                evh = new EventHandler(mapMaximizeAndPlay);
                storyboardShrinkMapping.Completed += evh;
                fFullScreenMoviePlayer = false;
                this.BeginStoryboard(storyboardShrinkMapping);
                

                MappingFrame.Visibility = Visibility.Visible;
                resultLabel.Visibility = Visibility.Visible;
            }
            else
            {
                
                this.UpdateCurrentClipBySegmentId(info.idSegment);
                SetMovie(info);
            }

            int val = (int)sliderMoviePosition.Value;
            mediaMoviePlayer.Position = new TimeSpan(0, 0, 0, 0, val);
        }

        void mapMaximizeAndPlay(object sender, EventArgs e)
        {
            cmdFullScreenMoviePlayer.Visibility = Visibility.Hidden;
            cmdRestoreScreenMoviePlayer.Visibility = Visibility.Visible;

            MappingFrame.Visibility = Visibility.Hidden;
            resultLabel.Visibility = Visibility.Hidden;
            fFullScreenMoviePlayer = true;
            Storyboard storyboardFullScreenMoviePlayer = FindResource("TimelineFullScreenMoviePlayer") as Storyboard;
            storyboardFullScreenMoviePlayer.Completed += new EventHandler(mapMaximizeAndPlay2);
            this.BeginStoryboard(storyboardFullScreenMoviePlayer);
        }

        void mapMaximizeAndPlay2(object sender, EventArgs e)
        {
            SetMovie(theMovieInfo);
            PlayMovie();
            storyboardShrinkMapping.Completed -= evh;
        }


        






		void mapCanvasText_LostFocus(object sender, RoutedEventArgs e)
		{
			TextBox tbRemove = sender as TextBox;
			if (tbRemove == null || tbRemove.Text != string.Empty)
			{
				Debug.Assert(tbRemove != null);
				return;
			}

			inkCnvsMapping.Children.Remove(tbRemove);
		}


		private TextBox AddTextElementToMappingCanvas(string text, Point point)
		{
			TextBox elmText = shapeManager.CreateTextBoxElement() as TextBox;
			if (elmText == null)
			{
				Debug.Assert(false);
				return null;
			}
			elmText.Text = "TEXT";
			AddDrawingElementToMappingCanvas(elmText);
			InkCanvas.SetLeft(elmText, point.X);
			InkCanvas.SetTop(elmText, point.Y);
			inkCnvsMapping.UpdateLayout();

			elmText.Text = text;
            elmText.Foreground = colorPicker.PickedBrush;
			elmText.LostFocus += new RoutedEventHandler(mapCanvasText_LostFocus);
			return elmText;
		}

		private void SetElementToTextBox(TextBox tb)
		{
			shapeManager.SetElementToTextBox(tb);
		}

		
		
		
		
		
		
		
		private void AddDrawingElementToMappingCanvas(UIElement element)
		{
			int i = inkCnvsMapping.Children.Count;
			for (; i > 0; i--)
			{
				if (inkCnvsMapping.Children[i-1].GetType() != typeof(Image))
					break;
			}
			inkCnvsMapping.Children.Insert(i, element);
		}

		void inkCnvsMapping_MouseMove(object sender, MouseEventArgs e)
		{
			Point ptMouse = e.GetPosition(inkCnvsMapping);

			if (e.LeftButton == MouseButtonState.Pressed && elDragging != null && ptMouse != ptMouseStart && shapeManager.Mode != MVExplorer.Shapes.DrawingMode.Text)
			{
				fMappingDrawing = true;
				double left = Math.Min(ptMouse.X, ptMouseStart.X);
				double top = Math.Min(ptMouse.Y, ptMouseStart.Y);
				double right = Math.Max(ptMouse.X, ptMouseStart.X);
				double bottom = Math.Max(ptMouse.Y, ptMouseStart.Y);
				if (MappingDrawingMode == MVExplorer.Shapes.DrawingMode.Arrow)
				{
					shapeManager.MoveShape(elDragging, ptMouseStart, ptMouse);
					RotateTransform rotation = elDragging.RenderTransform as RotateTransform;
					
					InkCanvas.SetLeft(elDragging, ptMouseStart.X - rotation.CenterX);
					InkCanvas.SetTop(elDragging, ptMouseStart.Y - rotation.CenterY);
				}
				else
				{
					InkCanvas.SetLeft(elDragging, left);
					InkCanvas.SetTop(elDragging, top);
					elDragging.Width = right - left;
					elDragging.Height = bottom - top;
					shapeManager.MoveShape(elDragging, ptMouseStart, ptMouse);
				}

			}
		}

		public Shapes.DrawingMode MappingDrawingMode
		{
			get { return shapeManager.Mode; }
			set { shapeManager.Mode = value; }
		}

		#endregion 

		#region KeywordBasket Panel Members

		private void InitKeywordBasketPanel()
		{
			
			
			
			
			
			
			
		}
        /*
		void cmdDeleteIdeaKeyword_Drop(object sender, DragEventArgs e)
		{
			string keyword = GetDraggingNodeKeyword(e);
			if (keyword == null)
				return;

			connector.DeleteIdeaBasketKeyword(keyword);
			UpdateUserKeywords();
		}

		void cmdAddIdeaKeyword_Click(object sender, RoutedEventArgs e)
		{
			Button btn = sender as Button;
			if (btn == null)
			{
				Debug.Assert(false);
				return;
			}
			AddIdeaKeyword(btn, textSearchKeyword.Text);
		}

		private void AddIdeaKeyword(Button btnAdd, string keyword)
		{
			

			

			

			
			
			
			
			
			
			

			
			
			
		}

		
		
		
		
		
		
		
		
		
		
		
		
		

		
		
		
		
		
		
		

		
		
		
		
		
		
		
		
		
        */
/*
		private void UpdateScrollButtonState()
		{
			ScrollViewer scrViewer = VisualTreeHelper.GetChild(listKeywordBasket, 0) as ScrollViewer;
			
			if (scrViewer.HorizontalOffset == 0)
				cmdScrollLeftKeywordBasket.Visibility = Visibility.Hidden;
			else
				cmdScrollLeftKeywordBasket.Visibility = Visibility.Visible;
			if (scrViewer.HorizontalOffset + scrViewer.ViewportWidth >= scrViewer.ExtentWidth)
				cmdScrollRightKeywordBasket.Visibility = Visibility.Hidden;
			else
				cmdScrollRightKeywordBasket.Visibility = Visibility.Visible;
	
		}

        void scrviewKeywordBasket_ScrollChanged(object sender, ScrollChangedEventArgs e)
		{
			UpdateScrollButtonState();
		}

		void cmdScrollLeftKeywordBasket_Click(object sender, RoutedEventArgs e)
		{
			ScrollPageLeftList(listKeywordBasket);
		}

		void cmdScrollRightKeywordBasket_Click(object sender, RoutedEventArgs e)
		{
			ScrollPageRightList(listKeywordBasket);
		}

		void cmdDeleteIdeaKeyword_Click(object sender, RoutedEventArgs e)
		{
			XmlLinkedNode node = listKeywordBasket.SelectedItem as XmlLinkedNode;
			if (node != null && node["keyword"] != null && node["keyword"].InnerText != "")
				connector.DeleteIdeaBasketKeyword(node["keyword"].InnerText);
			UpdateUserKeywords();
		}



        void basketItemLink_Click(object sender, RoutedEventArgs e)
		{
			Hyperlink hlink = sender as Hyperlink;
			Debug.Assert(hlink != null);
			if (hlink != null)
			{
				XmlElement xelmSelected = SelectBasketItemFromButton(hlink.DataContext);
				if (xelmSelected != null)
				{
					XmlNode node = xelmSelected["keyword"];
					if (node != null)
						QuerySegmentByKeyword(node.InnerText);
				}
			}
		}

		void listKeywordBasket_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			
			
			

			
			
			
			
			
			

		}

		private XmlElement SelectBasketItemFromButton(object datacontext)
		{
			for (int i = 0; i < listKeywordBasket.Items.Count; i++)
			{
				XmlElement xelm = listKeywordBasket.Items[i] as XmlElement;
				if (datacontext == xelm)
				{
					listKeywordBasket.SelectedIndex = i;
					return xelm;
				}
			}
			return null;
		}

		private bool IsSelectedBasketItem(object datacontext)
		{
			if (GetBasketItemIndex(datacontext) == listKeywordBasket.SelectedIndex)
				return true;
			else
				return false;
		}

		private int GetBasketItemIndex(object datacontext)
		{
			for (int i = 0; i < listKeywordBasket.Items.Count; i++)
			{
				XmlElement xelm = listKeywordBasket.Items[i] as XmlElement;
				if (datacontext == xelm)
				{
					return i;
				}
			}
			return -1;
		}

		private bool fBasketItemMouseDown = false;

		void basketItem_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
		{
			Grid item = sender as Grid;
			Debug.Assert(item != null);
			Mouse.Capture(item, CaptureMode.SubTree);
			fBasketItemMouseDown = true;
		}

		void basketItem_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
		{
			Mouse.Capture(null);

			fBasketItemMouseDown = false;
		}

		void basketItem_MouseMove(object sender, MouseEventArgs e)
		{
			Grid item = sender as Grid;
			Debug.Assert(item != null);
			if (fBasketItemMouseDown && IsSelectedBasketItem(item.DataContext))
			{
				e.Handled = true;
				fBasketItemMouseDown = false;
				
				XmlLinkedNode node = item.DataContext as XmlLinkedNode;
				DataObject data = new DataObject();
				data.SetData(STR_DND_KEYWORDITEM_FORMAT, node);

				overlayElement = new DropPreviewAdorner((UIElement)MainGrid, item);
				if (draggingLayer == null)
					draggingLayer = AdornerLayer.GetAdornerLayer(MainGrid);
				draggingLayer.Add(overlayElement);

				DragDrop.DoDragDrop(item, data, DragDropEffects.Copy);

				draggingLayer.Remove(overlayElement);
				overlayElement = null;
			}
		}
        */
		#endregion 

		#region MoviePlayer Panel Members

		private System.Windows.Threading.DispatcherTimer timerMoviePlayer = new System.Windows.Threading.DispatcherTimer();
		private System.Windows.Threading.DispatcherTimer timerFFMoviePlayer = new System.Windows.Threading.DispatcherTimer();
		private System.Windows.Threading.DispatcherTimer timerRWMoviePlayer = new System.Windows.Threading.DispatcherTimer();
		private bool fUpdatingMovieSlider = false;
		private bool fMoviePlaying = false;
		private MovieInfo currentMovie;

		
		
		
		private void InitMoviePlayer()
		{
			mediaMoviePlayer.MediaOpened += new RoutedEventHandler(mediaMoviePlayer_MediaOpened);
            mediaMoviePlayer.BufferingStarted += new RoutedEventHandler(mediaMoviePlayer_BufferingStarted);
            mediaMoviePlayer.BufferingEnded += new RoutedEventHandler(mediaMoviePlayer_BufferingEnded);

			sliderMoviePosition.ValueChanged += new RoutedPropertyChangedEventHandler<double>(sliderMoviePosition_ValueChanged);
			cmdPlayMovie.Click += new RoutedEventHandler(cmdPlayMovie_Click);
			cmdPauseMovie.Click += new RoutedEventHandler(cmdPauseMovie_Click);

            
            
            

			timerFFMoviePlayer.Interval = new TimeSpan(5 * 1000 * 1000); 
			timerFFMoviePlayer.Tick += new EventHandler(timerFFMoviePlayer_Tick);
			timerRWMoviePlayer.Interval = new TimeSpan(5 * 1000 * 1000); 
			timerRWMoviePlayer.Tick += new EventHandler(timerRWMoviePlayer_Tick);
			cmdFastFowardMovie.PreviewMouseDown += new MouseButtonEventHandler(cmdFastFowardMovie_PreviewMouseDown);
			cmdFastFowardMovie.PreviewMouseUp += new MouseButtonEventHandler(cmdFastFowardMovie_PreviewMouseUp);
			cmdRewindMovie.PreviewMouseDown += new MouseButtonEventHandler(cmdRewindMovie_PreviewMouseDown);
			cmdRewindMovie.PreviewMouseUp += new MouseButtonEventHandler(cmdRewindMovie_PreviewMouseUp);


            cmdRestoreScreenMoviePlayer.Visibility = Visibility.Hidden;
		}

		private void RewindMovie()
		{
			mediaMoviePlayer.Position = new TimeSpan(mediaMoviePlayer.Position.Ticks - 50000 * 1000);
		}

		private void FastFowardMovie()
		{
			mediaMoviePlayer.Position = new TimeSpan(mediaMoviePlayer.Position.Ticks + 50000 * 1000);
		}

		void cmdRewindMovie_PreviewMouseDown(object sender, MouseButtonEventArgs e)
		{
			cmdRewindMovie.CaptureMouse();
			RewindMovie();
			timerRWMoviePlayer.Start();
			e.Handled = true;
		}

		void cmdRewindMovie_PreviewMouseUp(object sender, MouseButtonEventArgs e)
		{
			Mouse.Capture(null);
			timerRWMoviePlayer.Stop();
		}

		void timerRWMoviePlayer_Tick(object sender, EventArgs e)
		{
			if (Mouse.LeftButton == MouseButtonState.Pressed)
				RewindMovie();
			else
			{
				timerRWMoviePlayer.Stop();
				Mouse.Capture(null);
			}
		}

		void cmdFastFowardMovie_PreviewMouseDown(object sender, MouseButtonEventArgs e)
		{
			cmdFastFowardMovie.CaptureMouse();
			FastFowardMovie();
			timerFFMoviePlayer.Start();
			e.Handled = true;
		}

		void cmdFastFowardMovie_PreviewMouseUp(object sender, MouseButtonEventArgs e)
		{
			Mouse.Capture(null);
			timerFFMoviePlayer.Stop();
		}

        
		void timerFFMoviePlayer_Tick(object sender, EventArgs e)
		{
			if (Mouse.LeftButton == MouseButtonState.Pressed)
				FastFowardMovie();
			else
			{
				timerFFMoviePlayer.Stop();
				Mouse.Capture(null);
			}
		}

		internal void SetMovie(MovieInfo info)
		{
			if (info == null)
				return;

			
			if (string.IsNullOrEmpty(info.ThumbnailUrl))
				return;

            Debug.WriteLine("setmovie:" + info.MovieUrl);
			currentMovie = info;
			StopMovie();
			
			
			
			mediaMoviePlayer.Source = new Uri(info.ThumbnailUrl);
			mediaMoviePlayer.Play();
            
		}

		private void InitMovieSlider(bool fUpdatePreview)
		{
			if (currentMovie != null)
			{
				sliderMoviePosition.Maximum = (int)currentMovie.EndTime * 1000;
				sliderMoviePosition.Minimum = (int)currentMovie.StartTime * 1000;

				fUpdatingMovieSlider = !fUpdatePreview;
				sliderMoviePosition.Value = (int)currentMovie.StartTime * 1000;
				fUpdatingMovieSlider = false;
			}
		}

        
		void PlayMovie()
		{

            if (mediaMoviePlayer.NaturalDuration == Duration.Automatic)
			{
				if (currentMovie == null)	return;
				mediaMoviePlayer.Source = new Uri(currentMovie.MovieUrl);
                Debug.WriteLine("VIDEO:" + currentMovie.MovieUrl);
                history.AppendSegment(currentMovie.OriginalNode);
			}

            timerMoviePlayer.Start();
            cmdPlayMovie.Visibility = Visibility.Hidden;
            cmdPauseMovie.Visibility = Visibility.Visible;
            if (nsmp)
            {

                mediaMoviePlayer.Position = new TimeSpan(0, 0, 0, 0, (int)sliderMoviePosition.Value);
                nsmp = false;
            }

            fMoviePlaying = true;
			mediaMoviePlayer.Play();
            this.UpdateCurrentClipBySegmentId(currentMovie.idSegment);
		}

		void StopMovie()
		{
			cmdPauseMovie.Visibility = Visibility.Hidden;
			cmdPlayMovie.Visibility = Visibility.Visible;
			fMoviePlaying = false;
			mediaMoviePlayer.Stop();
		}

		void PauseMovie()
		{
			cmdPauseMovie.Visibility = Visibility.Hidden;
			cmdPlayMovie.Visibility = Visibility.Visible;
			fMoviePlaying = false;
			mediaMoviePlayer.Pause();
		}

		void cmdPlayMovie_Click(object sender, RoutedEventArgs e)
		{
			if (fMoviePlaying)
			{
				PauseMovie();
				Debug.Assert(false);
			}
			else
				PlayMovie();
		}

		void cmdPauseMovie_Click(object sender, RoutedEventArgs e)
		{
			if (fMoviePlaying)
				PauseMovie();
			else
			{
				PlayMovie();
				Debug.Assert(false);
			}
		}



        void cmdCmSound_Click(object sender, RoutedEventArgs e)
        {
            System.Console.WriteLine("sound ");
            try
            {
                String smPath = Environment.GetFolderPath(Environment.SpecialFolder.System) + "/sndvol.exe";
                Process.Start(smPath);
            }
            catch (Exception ex)
            {
            }
        }

		void mediaMoviePlayer_MediaOpened(object sender, RoutedEventArgs e)
		{
			if (mediaMoviePlayer.NaturalDuration != Duration.Automatic)
			{
				
				InitMovieSlider(true);
			}

			timerMoviePlayer.Stop();
			timerMoviePlayer.Interval = new TimeSpan(5 * 1000 * 1000); 
			timerMoviePlayer.Tick += new EventHandler(timerMoviePlayer_Tick);
			timerMoviePlayer.Start();
		}

        void mediaMoviePlayer_BufferingStarted(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("Buffering start");
            BufferingImage.Visibility = Visibility.Visible;
        }

        void mediaMoviePlayer_BufferingEnded(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("Buffering end");
            BufferingImage.Visibility = Visibility.Hidden;
        }
        
        void timerMoviePlayer_Tick(object sender, EventArgs e)
		{
			if (fUpdatingMovieSlider)
				return;
			if (mediaMoviePlayer.NaturalDuration == Duration.Automatic)
				return;
			fUpdatingMovieSlider = true;
			sliderMoviePosition.Value = mediaMoviePlayer.Position.TotalMilliseconds;
			if (currentMovie != null && sliderMoviePosition.Value >= (int)currentMovie.EndTime * 1000)
				PauseMovie();
			fUpdatingMovieSlider = false;
		}

		void sliderMoviePosition_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
		{
			if (!fUpdatingMovieSlider)
			{
				int val = (int)sliderMoviePosition.Value;
				if (mediaMoviePlayer.NaturalDuration == Duration.Automatic)
				{
					PlayMovie();
					PauseMovie();
				}
				mediaMoviePlayer.Position = new TimeSpan(0, 0, 0, 0, val);
			}
		}

        bool fFullScreenMoviePlayer = false;
		void cmdFullScreenMoviePlayer_Click(object sender, RoutedEventArgs e)
		{
            cmdFullScreenMoviePlayer.Visibility = Visibility.Hidden;
			cmdRestoreScreenMoviePlayer.Visibility = Visibility.Visible;

            MappingFrame.Visibility = Visibility.Hidden;
            resultLabel.Visibility = Visibility.Hidden;
            fFullScreenMoviePlayer = true;

            
            this.BeginStoryboard(storyboardFullScreenMoviePlayer);
		}

		void cmdRestoreScreenMoviePlayer_Click(object sender, RoutedEventArgs e)
		{
			cmdRestoreScreenMoviePlayer.Visibility = Visibility.Hidden;
			cmdFullScreenMoviePlayer.Visibility = Visibility.Visible;
            
            Storyboard storyboardShrinkMoviePlayer = FindResource("TimelineShirinkMoviePlayer") as Storyboard;
            if (presentationMode)
            {

                storyboardShrinkMoviePlayer.Completed += new EventHandler(backtoFullscreebMapping);
                presentationMode = false;
            }
            fFullScreenMoviePlayer = false;
			this.BeginStoryboard(storyboardShrinkMoviePlayer);

            MappingFrame.Visibility = Visibility.Visible;
            resultLabel.Visibility = Visibility.Visible;
           

        }

        void backtoFullscreebMapping(object sender, EventArgs e)
        {
            resultLabel.Visibility = Visibility.Hidden;
            cmdFullScreenMapping.Visibility = Visibility.Hidden;
            cmdRestoreScreenMapping.Visibility = Visibility.Visible;
            this.BeginStoryboard(storyboardFullScreenMapping);
            fFullScreenMapping = true;
        }

		#endregion

		#region Command Panel Members

		
		
		

        /*
        private void InitCommandPanel()
		{
			inkCnvsCommand.EditingMode = InkCanvasEditingMode.GestureOnly;
			inkCnvsCommand.Gesture += new InkCanvasGestureEventHandler(inkCnvsCommand_Gesture);
		}

		void inkCnvsCommand_Gesture(object sender, InkCanvasGestureEventArgs e)
		{
			foreach (GestureRecognitionResult r in e.GetGestureRecognitionResults())
			{
				if(r.ApplicationGesture == ApplicationGesture.RightDown)
				{
					PlayMovie();
					return;
				}
				else if (r.ApplicationGesture == ApplicationGesture.Down)
				{
					PauseMovie();
					return;
				}
			}
		}
        */
		#endregion 

		#region NewKeywordOverlay Members
        /*
		private enum NewKeywordOverlayMode
		{
			None,
			Cancel,
			SegmentKeyword,
			IdeaKeyword
		}
		
		private Storyboard storyboardShowNewKeywordOverlay;
		private Storyboard storyboardHideNewKeywordOverlay;
		private NewKeywordOverlayMode newKeywordMode = NewKeywordOverlayMode.None;
		private int idNewKeywordTargetSegment = -1;

        private void InitNewKeywordOverlay()
		{
			textNewKeyword.GotFocus += new RoutedEventHandler(textNewKeyword_GotFocus);
			storyboardShowNewKeywordOverlay = FindResource("ShowNewKeywordOverlay") as Storyboard;
			storyboardHideNewKeywordOverlay = FindResource("HideNewKeywordOverlay") as Storyboard;
			storyboardHideNewKeywordOverlay.Completed += new EventHandler(storyboardHideNewKeywordOverlay_Completed);
			cmdAddKeyword.Click += new RoutedEventHandler(cmdAddKeyword_Click);
			cmdCancelAddKeyword.Click += new RoutedEventHandler(cmdCancelAddKeyword_Click);
		}

		void textNewKeyword_GotFocus(object sender, RoutedEventArgs e)
		{
			textNewKeyword.SelectedText = RecognizeNKOverlayInkString();
		}

		private void ShowNewSegmentKeywordOverlay(int idSegment, string keyword)
		{
			idNewKeywordTargetSegment = idSegment;
			textNewKeyword.Text = keyword;
			ShowNewKeywordOverlay(NewKeywordOverlayMode.SegmentKeyword);
		}

		private void ShowNewIdeaKeywordOverlay(string keyword)
		{
			idNewKeywordTargetSegment = -1;
			textNewKeyword.Text = keyword;
			ShowNewKeywordOverlay(NewKeywordOverlayMode.IdeaKeyword);
		}

		private void ShowNewKeywordOverlay(NewKeywordOverlayMode mode)
		{
			newKeywordMode = mode;
			this.BeginStoryboard(storyboardShowNewKeywordOverlay);
		}

		private void HideNewKeywrodOverlay()
		{
			this.BeginStoryboard(storyboardHideNewKeywordOverlay);
		}

		void storyboardHideNewKeywordOverlay_Completed(object sender, EventArgs e)
		{
			string keyword = textNewKeyword.Text;
			if (string.IsNullOrEmpty(keyword))
				return;
			switch (newKeywordMode)
			{
				case NewKeywordOverlayMode.None:
					Debug.Assert(false);
					return;
				case NewKeywordOverlayMode.Cancel:
					idNewKeywordTargetSegment = -1;
					newKeywordMode = NewKeywordOverlayMode.None;
					return;
				case NewKeywordOverlayMode.SegmentKeyword:
					if (idNewKeywordTargetSegment < 0)
					{
						Debug.Assert(false);
						return;
					}
					if (connector.AddKeywordToSegment(idNewKeywordTargetSegment, keyword))
					{
						UpdateUserKeywords();
						ReQuerySegment();
					}
					return;
				case NewKeywordOverlayMode.IdeaKeyword:
					if (connector.AddKeywordToIdeaBasket(keyword))
					{
						QuerySegmentByKeyword(textSearchKeyword.Text);
						UpdateUserKeywords();
					}
					return;
			}
		}

		void cmdAddKeyword_Click(object sender, RoutedEventArgs e)
		{
			this.BeginStoryboard(storyboardHideNewKeywordOverlay);
		}

		void cmdCancelAddKeyword_Click(object sender, RoutedEventArgs e)
		{
			newKeywordMode = NewKeywordOverlayMode.Cancel;
			this.BeginStoryboard(storyboardHideNewKeywordOverlay);
		}

		private string RecognizeNKOverlayInkString()
		{
			if (inkCnvsNewKeywordBackground.Strokes.Count <= 0)
				return "";
			InkAnalyzer analyzer = new InkAnalyzer();
			analyzer.AddStrokes(inkCnvsNewKeywordBackground.Strokes);
			AnalysisStatus status = analyzer.Analyze();

			if (status.Successful)
			{
				string strRecognized = analyzer.GetRecognizedString();
				inkCnvsNewKeywordBackground.Strokes.Clear();
				return strRecognized;
			}
			return "";
		}
        */
		#endregion

		#region Data Provider Handlers

		private const string STR_SEGMENTMOVIES_PROVIDERNAME = "SegmentMovies";
		private const string STR_SEGMENTHISTORY_PROVIDERNAME = "SegmentHistory";
		private const string STR_SEGMENTBOOKMARK_PROVIDERNAME = "SegmentBookmark";

        private const string STR_CLIPSEGMENTS_PROVIDERNAME = "ClipSegments";
        private const string STR_RELATEDSEGMENTS_PROVIDERNAME = "RelatedSegments";
		private const string STR_USERKEYWORDS_PROVIDERNAME = "UserKeywords";
		private string currentKeyword = string.Empty;

		public void LoadMovieSource(string filename)
		{
			XmlDataProvider prov = GetDataProviderFromResource(STR_SEGMENTMOVIES_PROVIDERNAME);
			XmlDocument xdoc = new XmlDocument();
			xdoc.Load(filename);
			prov.Document = xdoc;
		}

		private void QuerySegmentByKeyword(string keyword)
		{
			if (string.IsNullOrEmpty(keyword))
				return;

			ChangeSortMode(SegmentSortMode.Alphabetical);

			Debug.Assert(ServerConnector != null);

            
            
            XmlDocument bd = ServerConnector.QueryBookmarks();
            if (bd == null) return;

            XmlNodeList list = bd.SelectNodes("/response/clips/clip/segment/id");
            int[] myBookmarkIds = new int[list.Count];
            int i=0;
            foreach (XmlNode node in list)
            {
                myBookmarkIds[i] = int.Parse(node.FirstChild.Value);
                
                i++;
            }

            XmlDocument md = ServerConnector.QuerySegmentByKeyword(keyword);
            if (md == null) return;

            XmlNodeList list2 = md.SelectNodes("/response/segments/clip/segment");
            foreach (XmlNode node in list2)
            {
                if (node.FirstChild.InnerText == null) continue;

                int sid = int.Parse(node.FirstChild.InnerText);
                int isMyBookmark = 0;
                foreach (int bsid in myBookmarkIds)
                {
                    
                    if (bsid == sid)
                    {
                        isMyBookmark =1;
                    }
                }

                XmlElement elm = md.CreateElement("mybookmark");
                elm.InnerText = isMyBookmark+"";
                node.AppendChild(elm);
                

            }

            this.MovieDocument = md;

            TextBlock resulttext = new TextBlock();

			if (this.MovieDocument == null || this.MovieDocument["response"] == null)
			{
                

                resulttext.Inlines.Add("no result");
                resultLabel.Content = resulttext;

                return;
			}

			int nResult = this.MovieDocument.GetElementsByTagName("segment").Count;
			currentKeyword = keyword;

			
			
			
            
			
			
			

            resulttext.Inlines.Add(string.Format("{0} results", nResult));
            resulttext.FontStyle = FontStyles.Italic;

            resultLabel.Content = resulttext;
              
			tabMovieListMode.SelectedItem = tabSearchResult;
		}

		void linkKeyword_Click(object sender, RoutedEventArgs e)
		{
			ReQuerySegment();
		}


		private void ReQuerySegment()
		{
			if (!string.IsNullOrEmpty(currentKeyword))
				QuerySegmentByKeyword(currentKeyword);
		}

		public XmlDocument MovieDocument
		{
			get { return GetDataProviderFromResource(STR_SEGMENTMOVIES_PROVIDERNAME).Document; }
			set { GetDataProviderFromResource(STR_SEGMENTMOVIES_PROVIDERNAME).Document = value; }
		}

		public XmlDocument HistoryDocument
		{
			get { return GetDataProviderFromResource(STR_SEGMENTHISTORY_PROVIDERNAME).Document; }
			set { GetDataProviderFromResource(STR_SEGMENTHISTORY_PROVIDERNAME).Document = value; }
		}

		public XmlDocument BookmarkDocument
		{
			get { return GetDataProviderFromResource(STR_SEGMENTBOOKMARK_PROVIDERNAME).Document; }
			set { GetDataProviderFromResource(STR_SEGMENTBOOKMARK_PROVIDERNAME).Document = value;
                if (value == null) return;
                XmlNodeList idlist = value.SelectNodes("/response/clips/clip/segment/id");
                Console.WriteLine(idlist.Count);

                Int16[] ids = new Int16[idlist.Count];
                for (int i = 0; i < idlist.Count; i++)
                {
                    ids[i] = Int16.Parse(idlist[i].InnerText);
                }

                this.bookmarkIds = ids;
            }
		}

        public XmlDocument ClipSegmentsDocument
        {
            get { return GetDataProviderFromResource(STR_CLIPSEGMENTS_PROVIDERNAME).Document; }
            set { GetDataProviderFromResource(STR_CLIPSEGMENTS_PROVIDERNAME).Document = value; }
        }

        public XmlDocument RelatedSegmentsDocument
        {
            get { return GetDataProviderFromResource(STR_RELATEDSEGMENTS_PROVIDERNAME).Document; }
            set { GetDataProviderFromResource(STR_RELATEDSEGMENTS_PROVIDERNAME).Document = value; }
        }

		private void UpdateUserKeywords()
		{
			Debug.Assert(ServerConnector != null);

			this.KeywordDocument = ServerConnector.QueryKeywords();
		}

		public XmlDocument KeywordDocument
		{
			get { return GetDataProviderFromResource(STR_USERKEYWORDS_PROVIDERNAME).Document; }
			set { GetDataProviderFromResource(STR_USERKEYWORDS_PROVIDERNAME).Document = value; }
		}

		public MeetCommon.Service.MeetServerConnector ServerConnector
		{
			set 
			{
				connector = value;
				if (connector != null)
					ReadMappingFromXaml();
            }
			get { return connector; }
		}

		private XmlDataProvider GetDataProviderFromResource(string providerName)
		{
			XmlDataProvider prov = this.FindResource(providerName) as XmlDataProvider;
			Debug.Assert(prov != null);
			return prov;
		}
        
		#endregion

        #region TakeSnapshot command
        private void OnTakingSnapshot(object sender, ExecutedRoutedEventArgs args)
        {
            if (fMoviePlaying)
            {
                PauseMovie();
            }
            Size size = new Size();
            MemoryStream stream = GetSnapshotAsPng(true, ref size, mediaMoviePlayer);
            
            
            
            if (stream != null)
            {
                Uri thumbnail_uri = mediaMoviePlayer.Source;

                Image imageElement = new Image();
                BitmapImage source = new BitmapImage();
                source.BeginInit();
                source.StreamSource = stream;
                source.EndInit();
                source.SourceRect = new Int32Rect(3, 3, (int)(size.Width - 6), (int)(size.Height - 6));
                imageElement.Source = source;
                imageElement.Width = 80d;
                imageElement.Height = 60d;
                imageElement.Tag = new MovieInfo(currentNode);
                Point pointForImage = FindVacantPoint();
                inkCnvsMapping.Children.Add(imageElement);
                InkCanvas.SetLeft(imageElement, pointForImage.X);
                InkCanvas.SetTop(imageElement, pointForImage.Y);
                
                inkCnvsMapping.EditingMode = InkCanvasEditingMode.Select;
                List<UIElement> selectionList = new List<UIElement>();
                selectionList.Add(imageElement);
                inkCnvsMapping.Select(selectionList);
            }
        }

        private void CanTakeSnapshot(object sender, CanExecuteRoutedEventArgs args)
        {
            if (mediaMoviePlayer.IsLoaded == true && fMoviePlaying)
            {
                args.CanExecute = true;
            }
            else
            {
                args.CanExecute = false;
            }
        }
        private MemoryStream GetSnapshotAsPng(bool putClipboard, ref Size sizePicture, FrameworkElement element)
        {
            if (!(element is MediaElement))
            {
                return null;
            }
            MediaElement media = element as MediaElement;

            MemoryStream stream = new MemoryStream();
            int marginX = (int)media.Margin.Left + (int)media.Margin.Right;
            int marginY = (int)media.Margin.Top + (int)media.Margin.Bottom;
            Size targetSize = media.RenderSize;
            
            
            int width = (int)targetSize.Width + marginX * 2;
            int height = (int)targetSize.Height + marginY;
            Matrix screenMatrix = PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice;
            System.Diagnostics.Debug.WriteLine(string.Format("dpi=({0:F0},{1:F0})", screenMatrix.M11, screenMatrix.M22));
            RenderTargetBitmap targetBmp = new RenderTargetBitmap(width, height, screenMatrix.M11 * 96d, screenMatrix.M22 * 96d, PixelFormats.Pbgra32);
            targetBmp.Render(media);
            if (putClipboard)
            {
                
                Clipboard.SetImage(targetBmp);
            }
            PngBitmapEncoder encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(targetBmp));
            encoder.Save(stream);
            
            sizePicture = new Size(width, height);
            stream.Seek(0, SeekOrigin.Begin);
            
            return stream;
        }

        private Point FindVacantPoint()
        {
            Point pointLast = new Point(10d, 20d);
            foreach (UIElement element in inkCnvsMapping.Children)
            {
                if (element is Image)
                {
                    double x = InkCanvas.GetLeft(element);
                    double y = InkCanvas.GetTop(element);
                    if (!double.IsNaN(x) && !double.IsNaN(y))
                    {
                        pointLast = new Point(x, y);
                    }
                }
            }
            pointLast.X += 20d;
            pointLast.Y += 20d;
            return pointLast;
        }
        #endregion
	}


    public class MapDrawing{
        private List<UIElement> elements = new List<UIElement>();

        public MapDrawing()
        {
        }

        public MapDrawing(List<UIElement> elms)
        {
            this.elements = elms;
        }

        public void Add(UIElement elm){
            this.elements.Add(elm);
        }

        public void remove(UIElement elm){
            this.elements.Remove(elm);
        }

        public List<UIElement> Elements{
            get { return this.elements; }
            set{ this.elements = value;}
        }

        public MapDrawing clone()
        {
            return new MapDrawing(this.elements);
        }
    }
}